package com.test.config;

import org.springframework.cache.Cache;
import org.springframework.cache.jcache.JCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.spi.CachingProvider;
import java.util.concurrent.TimeUnit;

@Configuration
public class EhcacheConfig {

    @Bean(destroyMethod = "close", name = "jsrCacheManager")
    public CacheManager cacheManager() {
        CachingProvider provider = Caching.getCachingProvider();
        CacheManager cacheManager = provider.getCacheManager();
        cacheManager.createCache("smsVerifyCode", mutableConfiguration());
        return cacheManager;
    }

    @Bean(name = "jCacheCacheManager")
    public JCacheCacheManager jCacheCacheManager() {
        JCacheCacheManager jCacheCacheManager = new JCacheCacheManager(cacheManager());
        return jCacheCacheManager;
    }

    private MutableConfiguration mutableConfiguration() {
        MutableConfiguration<Long, String> configuration =
                new MutableConfiguration<Long, String>()
                        .setTypes(Long.class, String.class)
                        .setStoreByValue(false)
                        .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.FIVE_MINUTES));
        return configuration;
    }

    public static void main(String... args) throws Exception {
        MutableConfiguration<Long, String> configuration =
                new MutableConfiguration<Long, String>()
                        .setTypes(Long.class, String.class)
                        .setStoreByValue(false)
                        .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 10)));
        CachingProvider provider = Caching.getCachingProvider();
        CacheManager cacheManager = provider.getCacheManager();
        cacheManager.createCache("smsVerifyCode", configuration);
        JCacheCacheManager jCacheCacheManager = new JCacheCacheManager(cacheManager);
        jCacheCacheManager.getCache("smsVerifyCode").put(13880827903L, "1234|1383929402340");
        System.out.println(jCacheCacheManager.getCache("smsVerifyCode").get(13880827903L).get().toString());
        String ss = jCacheCacheManager.getCache("smsVerifyCode").get(131880827903L, String.class);
        System.out.println(ss);
        for(int i = 0; i < 13; i++) {
            Cache.ValueWrapper vw = jCacheCacheManager.getCache("smsVerifyCode").get(13880827903L);
            if (vw != null) {
                System.out.println("[" + i +"]" + vw.get());
            } else {
                System.out.println("[" + i +"]" + "无");
            }
            Thread.sleep(1000);
        }
    }
}
